package com.xiaobaibai.units;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaobaibai.bo.BargainDelayItem;
import com.xiaobaibai.bo.OrderDelayItem;
import com.xiaobaibai.common.OrderCommon;
import com.xiaobaibai.common.OrderEnum;
import com.xiaobaibai.controller.OrderController;
import com.xiaobaibai.entity.BargainUser;
import com.xiaobaibai.service.IBargainUserService;
import com.xiaobaibai.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * 订单付款后三`天自动收货
 * 货到付款的订单就不用管了,因为配送人员会督促客户进行确认收货后付款的
 */
@Component
@Slf4j
@Order(999)
public class OrderAcceptDelayQueueUnit implements ApplicationRunner {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IOrderService orderService;

    private static final String waitAcceptOrder="waitAcceptOrderDelayQueue";

    private DelayQueue<OrderDelayItem> delayQueue=new DelayQueue<>();

    /**
     * 存入延时队列,用redis做半持久化
     */
    public void saveBargainDelayItem(OrderDelayItem orderDelayItem){
        //这里先右吞入redis,再加入队列,好像没区别,因为每个原子都可能断电
        String jsonStr=JSON.toJSONString(orderDelayItem);
        stringRedisTemplate.opsForList().rightPush(waitAcceptOrder,jsonStr);
        delayQueue.add(orderDelayItem);
    }

    private void consumerBargainItem(){
        while (true){
            try {
                OrderDelayItem orderDelayItem = delayQueue.take();
                //左吐出吐出redis
                stringRedisTemplate.opsForList().leftPop(waitAcceptOrder);//吐出一个任务
                String orderId = orderDelayItem.getOrderId();
                QueryWrapper<com.xiaobaibai.entity.Order> q1=new QueryWrapper<>();
                q1.select("order_id","user_id","user_phone","order_status","order_real_price","create_time");
                q1.eq("order_id",orderId);
                com.xiaobaibai.entity.Order order = orderService.getOne(q1);
                if(order.getOrderStatus().equals(OrderEnum.ING.getCode())){
                    stringRedisTemplate.opsForValue().set(OrderCommon.doOrderLock+order.getUserId(),"1",10, TimeUnit.SECONDS);
                    orderService.confirmGoods(order);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("自动收货队列异常");
            }
        }
    }

    @Override
    public void run(ApplicationArguments args) {
        //立马从redis中读入延时队列,宕机保护
        List<String> list = stringRedisTemplate.opsForList().range(waitAcceptOrder, 0, -1);
        if(list!=null) {
            list.forEach(l -> {
                OrderDelayItem orderDelayItem = JSON.parseObject(l, OrderDelayItem.class);
                delayQueue.add(orderDelayItem);
            });
        }
        //开始循环
        Thread thread=new Thread(this::consumerBargainItem);
        thread.start();
    }

}
